package com.moyun.modelclass.view.preview;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

public class STLFileReader {

    public static FloatBuffer parseSTLFile(String filePath) throws IOException {
        File file = new File(filePath);
        FileInputStream inputStream = new FileInputStream(file);

        byte[] header = new byte[80];
        byte[] numFacetsBytes = new byte[4];
        inputStream.read(header);
        inputStream.read(numFacetsBytes);

        int numFacets = ByteBuffer.wrap(numFacetsBytes).order(ByteOrder.LITTLE_ENDIAN).getInt();
        ByteBuffer buffer = ByteBuffer.allocate(50 * numFacets).order(ByteOrder.LITTLE_ENDIAN);
        inputStream.read(buffer.array());

        FloatBuffer verticesBuffer = ByteBuffer.allocateDirect(numFacets * 9 * 4).order(ByteOrder.nativeOrder()).asFloatBuffer();

        for (int i = 0; i < numFacets; i++) {
            buffer.position(i * 50 + 12);
            for (int j = 0; j < 9; j++) {
                verticesBuffer.put(buffer.getFloat());
            }
        }

        verticesBuffer.position(0);
        inputStream.close();
        return verticesBuffer;
    }
}

